<template>
  <div>
       <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片区域 -->
             
            <el-card>
               <el-row>
                 <el-button type="primary" @click="showAddCateDialog()">添加分类</el-button>
               </el-row>
               <!-- 表格区域 -->
                <tree-table :data="cateList" :columns="columns" :selection-type=false
                :expand-type="false" show-index index-text="#" border class="treeTable" :show-row-hover="false">
                  <!-- 是否有效 -->
                   <template slot="isok" slot-scope="scope">
                          <i v-if="!scope.row.cat_deleted" class="el-icon-success" style="color:#61ce51"></i>
                          <i v-if="scope.row.cat_deleted" class="el-icon-error" style="color:red"></i>
                   </template>
                    <!-- 排序 -->
                      <template  slot="order" slot-scope="scope"> 
                          <el-tag v-if="scope.row.cat_level==0" >一级</el-tag>
                          <el-tag v-if="scope.row.cat_level==1" type="success">二级</el-tag>
                          <el-tag v-if="scope.row.cat_level==2" type="warning">三级</el-tag>
                     </template>
                     <!-- 操作 -->
                          <template slot="opt" slot-scope="scope">
                             <el-button @click="showEditCateDialog(scope.row)"  type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                             <el-button @click="removeCate(scope.row.cat_id)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                              
                              
                          </template>
                </tree-table>
                <!-- 分页区域 -->
                  <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="queryInfo.pagenum"
                  :page-sizes="[1, 2, 5, 10]"
                  :page-size="queryInfo.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
                  </el-pagination>
        </el-card>
        <!-- 添加分类对话框 -->
        <el-dialog
          title="添加分类"
          :visible.sync="addCateDialogVisible"
          width="50%" @close = "clearAddCateForm">
            <!-- 表单区域 -->
              <el-form ref="addCateFormRef" :model="addCateform" label-width="80px" :rules="addCateRules">
                  <el-form-item label="分类名称" prop="cat_name">
                      <el-input v-model="addCateform.cat_name"></el-input>
                  </el-form-item>
                  <el-form-item label="父级分类">
                     <!-- 级联选择器 -->
                        <!-- options指定数据源,props指定配置对象 -->
                      <el-cascader
                        v-model="selectedKeys"
                        :options="parentCateList"
                        @change="cateHandleChange"
                        expand-trigger="hover"
                        :props="cascaderProps" clearable >
                      </el-cascader>
                  </el-form-item>
              </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCate">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑分类对话框 -->
        <el-dialog
            title="编辑分类"
            :visible.sync="editDialogVisible"
            width="50%">
            <el-form ref="editFormRef" :model="eidtCateForm" :rules="addCateRules">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="eidtCateForm.cat_name"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editCate">确 定</el-button>
            </span>
          </el-dialog>
  </div>
</template>

<script>
export default {
       data() {
           return {
              // 查询条件
               queryInfo:{
                 type:3,
                 pagenum:1,
                 pagesize:5
               },
               //分类信息  
               cateList:[],
               //父级分类信息
               parentCateList:[],  
               //级联选择器的Props对象
               cascaderProps:{
                  value:'cat_id',
                  label:'cat_name',
                  children:'children',
                  checkStrictly:true
               },  
               //选中的父级分类的Id数组
               selectedKeys:[],  
               //总数据条数
               total:0,
               //表格数据配置 
               columns:[
                  {
                  label:'分类名称',
                  prop: 'cat_name'
                  },
                  {
                  label:'是否有效',
                  // 将当前列定义为模板列
                  type:'template',
                  //当前这列使用的模板名称
                  template:'isok'
                  },
                  {
                  label:'排序',
                  // 将当前列定义为模板列
                  type:'template',
                  //当前这列使用的模板名称
                  template:'order'
                  },
                  {
                  label:'操作',
                  // 将当前列定义为模板列
                  type:'template',
                  //当前这列使用的模板名称
                  template:'opt'
                  }
                ],
               //控制添加分类对话框显示
               addCateDialogVisible:false,
               //控制编辑分类对话框显示  
               editDialogVisible:false,
               //当前编辑的分类对象
               eidtCateForm:{},  
               //添加分类表单对象
               addCateform:{
                  //  默认添加的分类是一级分类
                    cat_name:'',
                    cat_pid:0,
                    cat_level:0

               },
               //添加分类表单的验证规则对象
               addCateRules:{
                cat_name:[{
                  required:true,message:'请输入分类名称',trigger:'blur'
                }
                ]
               }
              

               
           }
       },
       created() {
          this.getCateList();
       },
       methods: {
           async getCateList(){
            const {data:res} = await this.$http.get('categories',{params:this.queryInfo});
            if(res.meta.status !== 200 ) return this.$message.error('获取分类信息失败')
            this.$message.success('获取分类信息成功')
            this.cateList = res.data.result;
            this.total = res.data.total;
            console.log(res.data);
            
           },
          // 监听pagesize变化 
           handleSizeChange(newSize){
              this.queryInfo.pagesize = newSize;
              this.getCateList();
           },
          //  监听pagenum变化
           handleCurrentChange(newPageNum){
             this.queryInfo.pagenum = newPageNum;
             this.getCateList();
           },
          //  显示添加分类对话框
          showAddCateDialog(){
             this.getParentCateList();
             this.addCateDialogVisible = true;
          },
          //  获取父级分类的数据列表
          async getParentCateList(){
             const {data:res} = await this.$http.get('categories',{params:{type:2}});
             if(res.meta.status !== 200) return;
             this.parentCateList = res.data;
             console.log(this.parentCateList);
          },
          //级联选择器选项发生变化时的回调
          cateHandleChange(){
               console.log(this.selectedKeys);
               //当有父分类时 
               if(this.selectedKeys.length > 0){
                  // 赋值给预提交表单
                  this.addCateform.cat_pid = this.selectedKeys[this.selectedKeys.length-1];
                  this.addCateform.cat_level = this.selectedKeys.length;
 
               }else{
                  this.addCateform.cat_pid = 0;
                  this.addCateform.cat_level = 0;
               }
             
          },  
          //点击添加新分类
          addCate(){
            this.$refs.addCateFormRef.validate(async valid=>{
               if(!valid) return;
               const {data:res} = await this.$http.post('categories',this.addCateform);
               if(res.meta.status !== 201 ) return this.$message.error('添加分类失败');
               this.$message.success('添加分类成功');
               this.getCateList();
               this.addCateDialogVisible = false;
            })   
          },
          // 清空表单数据
          clearAddCateForm(){
            //清空预提交表单
             this.$refs.addCateFormRef.resetFields();
             this.selectedKeys = [];
             this.addCateform.cat_pid = 0;
             this.addCateform.cat_level =0;
            
          },
          //删除对应的分类
          removeCate(cateId){
              this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then( async() => {
               const {data:res} = await this.$http.delete(`categories/${cateId}`);
               if(res.meta.status !== 200 ) return this.$message.error('删除失败');
               this.getCateList();
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });
      
          },
          //显示编辑分类对话框
          showEditCateDialog(editCate){
             console.log(editCate);
             this.eidtCateForm = editCate;
             this.editDialogVisible = true;
          },
          //点击编辑分类
          editCate(){
            this.$refs.editFormRef.validate( async valid=>{
               if(!valid) return;
               const {data:res} = await this.$http.put(`categories/${this.eidtCateForm.cat_id}`,{cat_name:this.eidtCateForm.cat_name});
               console.log(res);
               if(res.meta.status !== 200 ) return this.$message.error('编辑分类失败');
               this.$message.success('编辑分类成功');
               this.editDialogVisible = false;
               this.getCateList();
               
            })
          }
          
       },
}
</script>

<style lang="less" scoped>
       .treeTable{
         margin-top: 15px;
       }
       .el-pagination{
          position: relative;
          left: 22%;
       }
</style>